package py.edu.ucom.cadira.net;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import org.jdom.JDOMException;

import py.edu.ucom.cadira.net.NetListener;
import py.edu.ucom.cadira.net.XMLSerializable;
import py.edu.ucom.cadira.xml.BadProtocolException;


public class ConexionClient extends Conexion {

	private NetListener netListener;

	public ConexionClient(String ip, int port, NetListener netListener)
			throws UnknownHostException, IOException {
		socket = new Socket(ip, port);
		initializeStreams(socket);
		this.netListener = netListener;
	}

	public void run() {
		initializeStreams(socket);

		try {
			while (keepAlive) {

				XMLSerializable xmlSerializable = read();
				if (xmlSerializable == null) {
					keepAlive = false;
				} else {

					netListener.messageArrived(xmlSerializable);

				}

			}

		} catch (IOException e) {
			System.out.println("Error reading from conexion");
			e.printStackTrace();
		} catch (JDOMException e) {
			System.out.println("Error parsgin xml");
			e.printStackTrace();
		} catch (BadProtocolException e) {
			System.out.println("Bad protocol " + e.getMessage());
			e.printStackTrace();
		} finally {
			close();
		}
	}

}
